$(function() {
    var uri = document.location.pathname;   
    var savenewUri = uri+'/savenew';

    $('.toggle').click(function() {
        if($('.toggle').hasClass('add')) {
            $('.add-toggle').slideToggle('fast', function(){
                $('.add-toggle .editable').editable('toggleDisabled');
                $('.toggle').addClass('save');
                $('.toggle').removeClass('add');
                $('.toggle').attr('title', 'Enregistrer'); 
                $('.cancel').show();
            });
        } else if($('.toggle').hasClass('save')) {
            $('.add-toggle .editable').editable('submit', {
                url: savenewUri,
                ajaxOptions: {
                    dataType: 'json' //assuming json response
                },                
                error: function(errors) {
                    var msg = '';
                    if(errors && errors.responseText) { //ajax error, errors = xhr object
                        msg = errors.responseText;
                        $('#msg').addClass('alert-success').removeClass('alert-error').html(msg).show();
                        $('.add-toggle').slideToggle('fast', function(){
                            $('.add-toggle .editable').editable('toggleDisabled');
                            $('.toggle').addClass('add');
                            $('.toggle').removeClass('save');
                            $('.toggle').attr('title', 'Ajouter');
                        });
                        window.location.href = uri;
                    } else { //validation error (client-side or server-side)
                        $.each(errors, function(k, v) { msg += k+": "+v+"<br>"; });
                        $('#msg').removeClass('alert-success').addClass('alert-error').html(msg).show();
                    }
                }
            });
        }
    });
    
    $('.cancel').click(function() {
        $('.add-toggle').slideToggle('fast', function(){
            $('.add-toggle .editable').editable('toggleDisabled');
            $('.toggle').addClass('add');
            $('.toggle').removeClass('save');
            $('.toggle').attr('title', 'Ajouter'); 
            $('#msg').hide();
            $('.cancel').hide();            
        });
    });
});